<template>
  <div class="content-banners">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2>轮播图管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新增轮播图
        </el-button>
        <el-button type="success" @click="handleBatchPush">
          <el-icon><Upload /></el-icon>
          批量推送设备
        </el-button>
      </div>
    </div>

    <!-- 搜索条件 -->
    <div class="search-form">
      <el-form :model="queryParams" inline>
        <el-form-item label="轮播图标题">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadBannerList">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        :data="bannerList"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="120" />
        <el-table-column label="图片" width="120">
          <template #default="{ row }">
            <el-image
              :src="row.imageUrl"
              :preview-src-list="[row.imageUrl]"
              fit="cover"
              style="width: 80px; height: 45px; border-radius: 4px"
            >
              <template #error>
                <div class="image-error">图片加载失败</div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="primary" @click="handlePush(row)">
              <el-icon><Upload /></el-icon>
              推送设备
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadBannerList"
          @current-change="loadBannerList"
        />
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="轮播图标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="图片地址" prop="imageUrl">
          <el-input v-model="formData.imageUrl" placeholder="请输入图片URL" />
          <div style="margin-top: 8px">
            <el-button type="primary" @click="handleUploadImage">上传图片</el-button>
          </div>
        </el-form-item>
        <el-form-item label="跳转链接">
          <el-input v-model="formData.linkUrl" placeholder="请输入跳转链接（可选）" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="1" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 推送设备弹窗 -->
    <el-dialog
      title="推送轮播图到设备"
      v-model="pushDialogVisible"
      width="800px"
    >
      <div class="push-container">
        <!-- 设备选择 -->
        <div class="device-selection">
          <h4>选择目标设备</h4>
          <div class="device-list">
            <el-checkbox-group v-model="selectedDevices">
              <div class="device-grid">
                <el-checkbox
                  v-for="device in deviceList"
                  :key="device.id"
                  :label="device.id"
                  class="device-item"
                >
                  <div class="device-info">
                    <div class="device-name">{{ device.name }}</div>
                    <div class="device-code">{{ device.code }}</div>
                    <div class="device-location">{{ device.location }}</div>
                  </div>
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </div>

        <!-- 推送设置 -->
        <div class="push-settings">
          <h4>推送设置</h4>
          <el-form :model="pushSettings" label-width="100px">
            <el-form-item label="推送时间">
              <el-radio-group v-model="pushSettings.pushTime">
                <el-radio label="immediate">立即推送</el-radio>
                <el-radio label="schedule">定时推送</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="pushSettings.pushTime === 'schedule'" label="定时时间">
              <el-date-picker
                v-model="pushSettings.scheduleTime"
                type="datetime"
                placeholder="选择推送时间"
              />
            </el-form-item>
            <el-form-item label="推送模式">
              <el-radio-group v-model="pushSettings.pushMode">
                <el-radio label="replace">替换现有轮播图</el-radio>
                <el-radio label="append">追加到现有轮播图</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <el-button @click="pushDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePushConfirm" :loading="pushing">
          确认推送
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Upload, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import type { Banner, BannerForm, Device } from '@/types'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const pushDialogVisible = ref(false)
const submitting = ref(false)
const pushing = ref(false)
const formRef = ref<FormInstance>()
const selectedRows = ref<Banner[]>([])

// 查询参数
const queryParams = reactive({
  page: 1,
  size: 10,
  title: '',
  status: ''
})

// 表单数据
const formData = reactive<BannerForm>({
  title: '',
  imageUrl: '',
  linkUrl: '',
  sort: 1,
  status: 'active'
})

// 推送相关数据
const selectedDevices = ref<number[]>([])
const deviceList = ref<Device[]>([])
const pushSettings = reactive({
  pushTime: 'immediate',
  scheduleTime: '',
  pushMode: 'replace'
})

// 表单验证规则
const formRules: FormRules = {
  title: [
    { required: true, message: '请输入轮播图标题', trigger: 'blur' }
  ],
  imageUrl: [
    { required: true, message: '请输入图片地址', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 模拟数据
const bannerList = ref<Banner[]>([
  {
    id: 1,
    title: '欢迎使用智能回收箱',
    imageUrl: 'https://via.placeholder.com/800x400?text=Banner1',
    linkUrl: '',
    sort: 1,
    status: 'active',
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    title: '环保从我做起',
    imageUrl: 'https://via.placeholder.com/800x400?text=Banner2',
    linkUrl: '',
    sort: 2,
    status: 'active',
    createTime: '2024-01-16 14:20:00'
  },
  {
    id: 3,
    title: '垃圾分类指南',
    imageUrl: 'https://via.placeholder.com/800x400?text=Banner3',
    linkUrl: '',
    sort: 3,
    status: 'inactive',
    createTime: '2024-01-17 09:15:00'
  }
])

const total = ref(3)

// 计算属性
const dialogTitle = computed(() => formData.id ? '编辑轮播图' : '新增轮播图')

// 生命周期
onMounted(() => {
  loadBannerList()
  loadDeviceList()
})

// 方法定义
const loadBannerList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    loading.value = false
  } catch (error) {
    loading.value = false
    ElMessage.error('加载轮播图列表失败')
  }
}

const loadDeviceList = async () => {
  try {
    // 模拟设备数据
    deviceList.value = [
      {
        id: 1,
        code: 'DEV001',
        name: '智能回收箱-001',
        type: 'standard',
        location: 'A栋大厅',
        currentWeight: 45,
        maxCapacity: 100,
        status: 'online',
        lastMaintenanceTime: '2024-01-20 10:00:00'
      },
      {
        id: 2,
        code: 'DEV002',
        name: '智能回收箱-002',
        type: 'standard',
        location: 'B栋门口',
        currentWeight: 30,
        maxCapacity: 100,
        status: 'online',
        lastMaintenanceTime: '2024-01-19 15:30:00'
      },
      {
        id: 3,
        code: 'DEV003',
        name: '智能回收箱-003',
        type: 'large',
        location: 'C栋停车场',
        currentWeight: 80,
        maxCapacity: 200,
        status: 'offline',
        lastMaintenanceTime: '2024-01-18 09:00:00'
      }
    ]
  } catch (error) {
    ElMessage.error('加载设备列表失败')
  }
}

const handleCreate = () => {
  Object.assign(formData, {
    id: undefined,
    title: '',
    imageUrl: '',
    linkUrl: '',
    sort: 1,
    status: 'active'
  })
  dialogVisible.value = true
}

const handleEdit = (row: Banner) => {
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleDelete = async (row: Banner) => {
  try {
    await ElMessageBox.confirm('确定要删除这个轮播图吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 模拟删除操作
    const index = bannerList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      bannerList.value.splice(index, 1)
      total.value--
      ElMessage.success('删除成功')
    }
  } catch (error) {
    // 用户取消删除
  }
}

const handlePush = (row: Banner) => {
  selectedRows.value = [row]
  pushDialogVisible.value = true
}

const handleBatchPush = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要推送的轮播图')
    return
  }
  pushDialogVisible.value = true
}

const handleSelectionChange = (selection: Banner[]) => {
  selectedRows.value = selection
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 模拟保存操作
    await new Promise(resolve => setTimeout(resolve, 500))

    if (formData.id) {
      // 编辑
      const index = bannerList.value.findIndex(item => item.id === formData.id)
      if (index !== -1) {
        bannerList.value[index] = { ...formData as Banner }
      }
      ElMessage.success('编辑成功')
    } else {
      // 新增
      const newBanner: Banner = {
        ...formData,
        id: Math.max(...bannerList.value.map(item => item.id)) + 1,
        createTime: new Date().toLocaleString('zh-CN')
      }
      bannerList.value.unshift(newBanner)
      total.value++
      ElMessage.success('新增成功')
    }

    dialogVisible.value = false
  } catch (error) {
    // 验证失败
  } finally {
    submitting.value = false
  }
}

const handlePushConfirm = async () => {
  if (selectedDevices.value.length === 0) {
    ElMessage.warning('请选择要推送的设备')
    return
  }

  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要推送的轮播图')
    return
  }

  try {
    pushing.value = true

    // 模拟推送操作
    await new Promise(resolve => setTimeout(resolve, 1000))

    ElMessage.success(`成功推送 ${selectedRows.value.length} 个轮播图到 ${selectedDevices.value.length} 台设备`)
    pushDialogVisible.value = false
    selectedDevices.value = []
  } catch (error) {
    ElMessage.error('推送失败')
  } finally {
    pushing.value = false
  }
}

const handleUploadImage = () => {
  ElMessage.info('图片上传功能待实现')
}

const handleReset = () => {
  Object.assign(queryParams, {
    page: 1,
    size: 10,
    title: '',
    status: ''
  })
  loadBannerList()
}

const handleDialogClose = () => {
  dialogVisible.value = false
  formRef.value?.clearValidate()
}
</script>

<style lang="scss" scoped>
.content-banners {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: #303133;
    }
  }

  .search-form {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
  }

  .table-container {
    background: white;
    border-radius: 4px;
    padding: 20px;

    .image-error {
      width: 80px;
      height: 45px;
      background: #f5f7fa;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #909399;
      font-size: 12px;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .push-container {
    .device-selection {
      margin-bottom: 20px;

      h4 {
        margin: 0 0 15px 0;
        color: #303133;
      }

      .device-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 10px;
        max-height: 300px;
        overflow-y: auto;

        .device-item {
          padding: 10px;
          border: 1px solid #e4e7ed;
          border-radius: 4px;
          margin: 0;

          .device-info {
            .device-name {
              font-weight: 500;
              margin-bottom: 4px;
            }

            .device-code,
            .device-location {
              font-size: 12px;
              color: #909399;
            }
          }
        }
      }
    }

    .push-settings {
      h4 {
        margin: 0 0 15px 0;
        color: #303133;
      }
    }
  }
}
</style>
